package com.tutk.P2PCam264;

import java.util.Random;

public class XORUtil {

	
	public static String encoder(byte[] inbuf) {
		final StringBuilder builder = new StringBuilder();
		for (byte b : inbuf) {
			builder.append(String.format("%02x", b));
		}
		return builder.toString();
	}

	public static byte[] decoder(String instr) {
		byte[] result = new byte[128];
		int i, len = instr.length(), 
			nPos = 0;
		
		  for (i = 0; i < len; i+=2) {
			   result[nPos] = (byte)((Character.digit(instr.charAt(i), 16) << 4) + Character.digit(instr.charAt(i+1), 16));
			   nPos++;
			  }

		  
		  
//		for (i = 0; i < len; i++) {
//			if (instr.charAt(i) == '%') {
//				result[nPos] = (byte)((Character.digit(instr.charAt(i+1), 16) << 4)	+ Character.digit(instr.charAt(i+2), 16));
//				i = i+2;
//			}
//			else {
//				result[nPos] = (byte)instr.charAt(i);
//			}
//			nPos++;
//		}
		return result;
	}
	
	public static byte getXorKey(){
		Random random=new Random();
		byte[] res = new byte[1];
		random.nextBytes(res);
		byte result = res[0];
		return result;
	}

	public static String getXorKey2(){
		Random random=new Random();
		byte[] res = new byte[1];
		random.nextBytes(res);
		byte result = res[0];

		return byteToHex(result);
	}
	
	public static String byteToHex(byte b){
		String ss = "0";
		if(b<0){
			ss = Integer.toHexString(b&0XFF);
		}else{
			ss = Integer.toHexString(b);	
		}
		if(ss.length() == 1){
			ss="0"+ss;
		}
		return ss;
	}
	
	
	public static String byteArrToString(byte[] bb){
		StringBuffer str = new StringBuffer();
		
		for(int i=0;i<bb.length;i++){
			str.append(byteToHex(bb[i]));
		}
		
		return str.toString();
	}
	
	
	public static int getXorKeyForInt(byte b){
		return b&0XFF;
	}
	
	public static int XorEncrypt(byte xorKey ,byte data){
		int res = data ^ xorKey;
		return res;
	}
	
	public static byte[] XorEncrypt(byte xorKey ,byte[] data){
		for(int i=0;i<data.length;i++){
			data[i] = (byte) XorEncrypt(xorKey, data[i]);
		}
		return data;
	}
	
	
	public static byte[] getRandomByteArray(){
		Random random=new Random();
		byte[] res = new byte[128];
		random.nextBytes(res);
		return res;
	}
	
}
